package com.neu.servlet.wty;

import com.neu.service.wty.UserService;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "RegisterServlet", urlPatterns = {"/RegisterServlet.reg"})
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String u_tel=request.getParameter("u_tel");
        String u_pwd=request.getParameter("u_pwd");
        String again=request.getParameter("again");
        UserService userService=new UserService();
        if (!u_pwd.equals(again)){
            System.out.println("两次密码输入不一致");
            PrintWriter out = response.getWriter();
            JSONObject data = new JSONObject();
            try {
                data.put("status", "againError");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            out.println(data.toString());
        }else if (again.isEmpty()){
            System.out.println("请输入确认密码!");
            PrintWriter out = response.getWriter();
            JSONObject data = new JSONObject();
            try {
                data.put("status", "noAgain");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            out.println(data.toString());
        }else {
            boolean flag=userService.register(u_tel,u_pwd);
            if (flag){
                System.out.println("成功");
                //验证成功
                PrintWriter out = response.getWriter();
                JSONObject data = new JSONObject();
                try {
                    data.put("status", "success");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                out.println(data.toString());
            }
            else{
                System.out.println("失败");
                // 验证失败
                JSONObject data = new JSONObject();
                try {
                    data.put("status", "fail");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                PrintWriter out = response.getWriter();
                out.println(data.toString());
            }
        }
    }
@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}